﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mall.Infrastructure.Container;
using Mall.Infrastructure.Model;
using System.Web.Security;
using System.Web.Script.Serialization;
using System.Security.Principal;
using Sx.Mall.WebContract.Dto;
using Sx.Mall.WebContract;

namespace Sx.Mall.Web.Filter
{
    public class LoginHelper
    {
        private static LoginUser user = null;

        private static InterfaceContainer app = AppDomain.CurrentDomain.GetContainer();


        public static LoginUser GetUser()
        {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormsIdentity form = (FormsIdentity)HttpContext.Current.User.Identity;
                FormsAuthenticationTicket Ticket = form.Ticket;
                user = serializer.Deserialize<LoginUser>(Ticket.UserData);
                return user;
        }

        public static CommonResult Login(LoginUser dto)
        {
            CommonResult result = new CommonResult();
            result.IsResult = true;
            result.Message = "登陆成功";
            ILoginService service = app.GetSerivce<ILoginService>();
            var item = service.Login(dto.UserName, dto.pwd);
            if (item.IsResult)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
                    (1,  //版本号
                    FormsAuthentication.FormsCookieName,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                    true,
                    serializer.Serialize(item.Result),
                    FormsAuthentication.FormsCookiePath
                    );
                //Encrypt the ticket.
                String encTicket = FormsAuthentication.Encrypt(ticket);
                //Create the cookie.
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                cookie.Expires = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);
                cookie.Domain = FormsAuthentication.CookieDomain;
                HttpContext.Current.Response.Cookies.Add(cookie);

            }
            result.IsResult = item.IsResult;
            result.Message = item.Message;
            return result;
        }

     
        public static void LoginOut()
        {
            FormsAuthentication.SignOut();
            HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
            myCookie.Expires = DateTime.Now.AddDays(-1d);
            HttpContext.Current.Response.Cookies.Add(myCookie);
            user = null;

        }

        public static bool IsLogin()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;

        }
    }
} 